<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">
            <el-form-item label="省" prop="provinceId">
                <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
                    <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="市" prop="cityId">
                <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
                    <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="区/县" prop="prefectureId">
                <el-select v-model="queryParams.prefectureId" placeholder="请选择区/县" clearable>
                    <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button plain @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8" style="float:left">
            <el-col :span="1.5">
                <el-button plain icon="Download" @click="handleImport">导入</el-button>
            </el-col>
        </el-row>

        <div style="text-align: right;float: right;">
            <span>排列方式：</span>
            <el-radio-group v-model="queryParams.option" @change="handleQuery()">
                <el-radio label="0">行政区划</el-radio>
                <el-radio label="1">更新时间倒序</el-radio>
            </el-radio-group>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </div>

        <el-table v-loading="loading" :data="dataList" stripe @sort-change="sortChange">
            <el-table-column label="省" align="center" prop="province" />
            <el-table-column label="市" align="center" prop="city" />
            <el-table-column label="区（县）" align="center" prop="prefecture" />
            <el-table-column label="总人口（人）" align="center" prop="peoTotal" sortable="custom" />
            <el-table-column label="户均人口（人/户）" align="center" prop="peoAvgHouse" sortable="custom" />
            <el-table-column label="人均住房建筑面积（平方米/人）" align="center" prop="peoAvgArea" sortable="custom" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />

        <!-- 修改弹出框 -->
        <el-dialog :title="title" v-model="open" append-to-body>
            <p class="dialogTitle">{{ title }}</p>
            <el-form ref="populationCensusRef" :model="form" :rules="rules" label-width="150px"
                style="padding:0 40px 0px 20px">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="省" prop="province" label-width="100px">
                            <el-select v-model="form.province" placeholder="请选择省" @change="chooseProvince" disabled value-key="id">
                                <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市" prop="city" label-width="100px">
                            <el-select v-model="form.city" placeholder="请选择市" @change="chooseCity" disabled value-key="id">
                                <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区（县）" prop="prefecture" label-width="100px">
                            <el-select v-model="form.prefecture" placeholder="请选择区/县" disabled value-key="id">
                                <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="总人口（人）" prop="peoTotal">
                            <el-input v-model="form.peoTotal" placeholder="请输入总人口" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="户均人口（人/户）" prop="peoAvgHouse">
                            <el-input v-model="form.peoAvgHouse" placeholder="请输入户均人口" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="人均住房建筑面积（平方米/人）" prop="peoAvgArea">
                            <el-input v-model="form.peoAvgArea" placeholder="请输入人均住房建筑面积" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确定</el-button>
                    <el-button plain @click="cancel">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <p></p>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload"
                :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError"
                :on-success="handleFileSuccess" :auto-upload="false" drag>
                <el-icon class="el-icon--upload">
                    <upload-filled />
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate('人口普查数据模板.xlsx')">下载模板</el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button plain @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup name="populationCensus">
import { getProvince, getChildArea } from "@/api/system/division";
import { getLanderRoles, getLanderProvince } from "@/api/basedatamanage/common.js"
import { positiveInteger,positive2decimals } from "@/utils/history"
import { getToken } from "@/utils/auth";
import { getAllPeoData, updatePeoData, getPeoData, delPeoData } from "@/api/basedatamanage/populationCensus.js"
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const loading = ref(false);
const open = ref(false);
const total = ref(0);
const title = ref("");
const showSearch = ref(true);
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]);//区、县
/*** 用户导入参数 */
const upload = reactive({
    open: false,
    title: "",
    isUploading: false,
    headers: { token: "token " + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + "/peo/peoImportExcel"
});
const data = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        provinceId: '',
        cityId: '',
        prefectureId: '',
        option: '0',
        option1: undefined
    },
    form: {
        province: '',
        city: '',
        prefecture: '',
        peoTotal:'',
        peoAvgHouse:'',
        peoAvgArea:'',
    },
    rules: {
        province:[{requirred:true,message:'请选择省',trigger:'change'}],
        city:[{requirred:true,message:'请选择市',trigger:'change'}],
        prefecture:[{requirred:true,message:'请选择区/县',trigger:'change'}],
        peoTotal: [{ required: true, message: '请输入整数值', trigger: 'blur', validator: positiveInteger }],
        peoAvgHouse: [{ required: true, message: '请输入正确的数值，保留两位小数', trigger: 'blur', validator: positive2decimals }],
        peoAvgArea: [{ required: true, message: '请输入正确的数值，保留两位小数', trigger: 'blur', validator: positive2decimals }],
    }
})
const { queryParams, form, rules } = toRefs(data)
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    dataList.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
}

// 重置表单
function reset() {
    form.value = {
        province: '',
        city: '',
        prefecture: '',
        peoTotal:'',
        peoAvgHouse:'',
        peoAvgArea:'',
    }
    proxy.resetForm("populationCensusRef");
}


/** 查询人口普查数据列表 */
function getList() {
    loading.value = true;
    getAllPeoData(queryParams.value).then(response => {
        dataList.value = response.data.rows;
        total.value = response.data.total;
        loading.value = false;
    });
}
const sortChange = ({ prop, order }) => {
    if(prop == 'peoTotal'){
        queryParams.value.option = 2
    }else if(prop == 'peoAvgHouse'){
        queryParams.value.option = 3
    }else if(prop == 'peoAvgArea'){
        queryParams.value.option = 4
    }else {
        queryParams.value.option = undefined
    }
    
    if(order == 'ascending'){
        queryParams.value.option1 = 0
    }else if(order == 'descending'){
        queryParams.value.option1 = 1
    }else{
        queryParams.value.option1 = undefined
    }
    handleQuery()
}

// 修改
function handleUpdate(row) {
    reset();
    getDetail(row.dataPeoId)
}

function getDetail(id) {
    getPeoData(id).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改人口普查数据"
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
    var area = ''
    if(row.province==row.city){
        area=row.province + row.prefecture
    }else{
        area=row.province + row.city + row.prefecture
    }
    const id = row.dataPeoId;
    proxy.$modal.confirm('是否确认删除人口普查信息编号为"' + area + '"的数据项？').then(function () {
        return delPeoData(id);
    }).then((res) => {
        getList();
        proxy.$modal.msgSuccess('删除成功');
    }).catch(() => { });
};

/** 提交按钮 */
function submitForm() {
    proxy.$refs["populationCensusRef"].validate(valid => {
        if (valid) {
            updatePeoData(form.value).then(response => {
                proxy.$modal.msgSuccess("修改成功");
                open.value = false;
                getList();
            });
        }
    });
}

/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}

// 模板下载
function importTemplate(name) {
  proxy.download("/base/product/downloadExcel", {
    fileName:name
  }, name);
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

/** 打开导入表弹窗 */
function handleImport() {
    upload.title = "导入";
    upload.open = true;
}

/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在导入文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("导入文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$modal.closeLoading();
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  queryParams.value.page = 1;
  getList();
};


/** 获取省列表 */
function getProvinceData() {
    getProvince().then(response => {
        provinceData.value = response.data;
    });
}
function chooseProvince(value) {
    // console.log(value)
    queryParams.value.cityId = null;
    queryParams.value.prefectureId = null;
    cityData.value = [];
    areaData.value = [];
    getChildArea(value).then(response => {
        cityData.value = response.data;
    });
    //provinceData.value.map(item => {//遍历数据
    //  if (item.id == value) {
    //    if (item.name == "北京市" || item.name == "天津市" || item.name == "上海市" || item.name == "重庆市") {
    //      cityData.value.push(JSON.parse(JSON.stringify(item)));
    //    } else {
    //      getChildArea(value).then(response => {
    //        cityData.value = response.data;
    //      });
    //    }
    //    return;
    //  }
    //})
}

function chooseCity(value) {
    queryParams.value.prefectureId = null;
    areaData.value = [];
    getChildArea(value).then(response => {
        areaData.value = response.data;
    });
}
// 权限
const isAdmin = async () => {
    let res = await getLanderRoles()
    const { code, data } = res
    if(code == 200) {
        const auth = data.split(',')
        return auth
    }else {
        return Promise.reject(new Error(data))
    }
}
const getDefaultProvice = async () => {
    try {
        let curAuth = await isAdmin()
        const type1 = curAuth.length == 1 && (curAuth.includes('省管理员') || curAuth.includes('省业务员'))
        const type2 = curAuth.length == 2 && curAuth.includes('省管理员') && curAuth.includes('省业务员')
        if(type1 || type2){
            getLanderProvince().then(res => {
                if(res.code == 200){
                    queryParams.value.provinceId = res.data
                    chooseProvince(queryParams.value.provinceId)
                    getList()
                }
            })
        }else{
            getList()
        }
    } catch (error) {
        
    }
}

getDefaultProvice();
getProvinceData();
</script>
  
<style lang="scss" scoped>
</style>